package com.bmw.regist.common.exception;

import com.bmw.regist.common.base.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
    @ExceptionHandler(BindException.class)
    public BaseResponse handlerBindException(BindException exception) {
        return handlerNotValidException(exception);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse handlerArgumentValidException(MethodArgumentNotValidException exception){
        return handlerNotValidException(exception);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse exception(Throwable throwable){
        log.error("系统异常",throwable);
        return BaseResponse.error(306,"服务器太忙碌了");
    }

    public BaseResponse handlerNotValidException(Exception e){
        log.debug("begin resolve argument exception");
        BindingResult result;
        if(e instanceof BindException){
            BindException exception=(BindException) e;
            result=exception.getBindingResult();
        }
        else {
            MethodArgumentNotValidException exception=(MethodArgumentNotValidException) e;
            result=exception.getBindingResult();
        }
        Map<String,Object> maps;
        if(result.hasErrors()){
            List<FieldError> fieldErrors=result.getFieldErrors();
            maps=new HashMap<>(fieldErrors.size());
            fieldErrors.forEach(error ->{
                maps.put(error.getField(),error.getDefaultMessage());
            });
        }
        else {
            maps= Collections.EMPTY_MAP;
        }
        return BaseResponse.error(305,"参数错误",maps);
    }
}

